#include "mb.h"
#include "comm.h"
#include "thread_manager.h"
#include "host_data_type.h"

#define DBG_TAG    "comm_pc"
#define DBG_LVL    DBG_INFO
#include <rtdbg.h>

struct MBBaudrate
{
    rt_uint8_t id;
    rt_uint32_t value;
};
static const struct MBBaudrate mbBaudrate[] = 
{
    {MB_Baudrate_ID_2400, 2400},
    {MB_Baudrate_ID_4800, 4800},
    {MB_Baudrate_ID_9600, 9600},
    {MB_Baudrate_ID_19200, 19200},
    {MB_Baudrate_ID_38400, 38400},
};
static struct serial_configure serial_config = RT_SERIAL_CONFIG_DEFAULT;
struct rt_serial_device *pc_serial_dev;

static rt_err_t serial_rx_callback(rt_device_t dev, rt_size_t size)
{
    struct Msg_Serial msg;
    rt_err_t result;
    msg.dev = dev;
    msg.size = size;
    result = rt_mq_send(&mb_rx_mq, &msg, sizeof(msg));
    
    return result;
}
void comm_pc_init(void)
{
    pc_serial_dev = (struct rt_serial_device *)rt_device_find("uart6");
    if(pc_serial_dev == RT_NULL) 
    {
        LOG_E("can't find %s device!\n", "uart6");
        return;
    }
    serial_config.baud_rate = mbBaudrate[regHoldBuf[ARG_ID_MBBaudrateID]- MB_Baudrate_ID_2400].value;
    rt_device_control(&pc_serial_dev->parent, RT_DEVICE_CTRL_CONFIG, &serial_config);

    rt_device_open((rt_device_t)pc_serial_dev, RT_DEVICE_FLAG_DMA_RX);

    rt_device_set_rx_indicate(&pc_serial_dev->parent, serial_rx_callback);
}
void comm_pc_set_baudrate(rt_uint32_t baudrate)
{
    if(serial_config.baud_rate != baudrate)
    {
        serial_config.baud_rate = baudrate;
        rt_device_control(&pc_serial_dev->parent, RT_DEVICE_CTRL_CONFIG, &serial_config);
    }
}
